package com.project.sianet.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import com.project.sianet.MainActivity;
import com.project.sianet.R;
import com.project.sianet.data.CompetenciaArrayAdapter;
import com.project.sianet.data.Client.LibretaClient;
import com.project.sianet.data.HttpClient.LibretaHttpClient;
import com.project.sianet.entidades.Competencia;
import com.project.sianet.entidades.Libreta;
import com.project.sianet.util.ConnectionDetector;
import com.project.sianet.util.SessionManager;
import com.project.sianet.util.extenders.SianetApplication;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpVersion;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

public class LibretaDetalleCriteriosFragment extends Fragment {

    private int mBimestre, mCGCodigo;
    private int mSubTitleFrag;
	private String mTitleFrag;
	private String mLogin, lastRequestURI;
	private Libreta mLibreta;
	private String mNomBim;
	private LibretaClient client;
	
	// Clase Connection detector
    ConnectionDetector cd;
    
    public LibretaDetalleCriteriosFragment() {}
    
    public static final LibretaDetalleCriteriosFragment newInstance(String login, int bim, Libreta lib, String titleFrag, int subTitleFrag, String nomBim) {
    	LibretaDetalleCriteriosFragment f = new LibretaDetalleCriteriosFragment();
    	Bundle args = new Bundle();
    	args.putInt("mBimestre", bim);
    	args.putString("mLogin", login);
		args.putString("mTitleFrag", titleFrag);
		args.putInt("mSubTitleFrag", subTitleFrag);
		args.putParcelable("mLibreta", lib);
		args.putString("mNomBim", nomBim);
		args.putInt("mCGCodigo", lib.getCodigoCurso());
		f.setArguments(args);
    	return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    	return inflater.inflate(R.layout.fragment_competencias, container, false);
        
	}
    
    @Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		// Creo la instancia de Connection detector
        cd = new ConnectionDetector(getActividad().getApplicationContext());
        
        mBimestre = getArguments().getInt("mBimestre");
    	mLogin = getArguments().getString("mLogin");
		mTitleFrag = getArguments().getString("mTitleFrag");
		mSubTitleFrag = getArguments().getInt("mSubTitleFrag");
		mLibreta = getArguments().getParcelable("mLibreta");
		mNomBim = getArguments().getString("mNomBim");
		mCGCodigo = getArguments().getInt("mCGCodigo");
		
		TextView title = (TextView)this.getActivity().findViewById(R.id.tv_title);
		TextView subtitle = (TextView)this.getActivity().findViewById(R.id.tv_subTitle);
		TextView ftvCurso = (TextView)this.getActivity().findViewById(R.id.ftv_comp_curso);
		TextView ftvBim = (TextView)this.getActivity().findViewById(R.id.ftv_comp_bim);
		
		if (TextUtils.isEmpty(mTitleFrag)) {
			title.setText(mSubTitleFrag);
		} else {
			subtitle.setVisibility(View.VISIBLE);
			title.setText(mTitleFrag);
			title.setMaxLines(1);
			title.setTextSize(16);
			subtitle.setText(mSubTitleFrag);
		}
		
		ftvCurso.setText(TextUtils.isEmpty(mLibreta.getCurso()) ? mLibreta.getArea() : mLibreta.getCurso());
		ftvBim.setText(mNomBim.toUpperCase(Locale.getDefault()));
		
		new TareaWSCargarLibretaDetalleNotas().execute();
		
    }
    
    class TareaWSCargarLibretaDetalleNotas extends AsyncTask<String,Integer,List<Competencia>> {
        private ProgressDialog progressDialog;
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            
            progressDialog = new ProgressDialog(getActividad());
            progressDialog.setCancelable(false);
            progressDialog.show();        
            progressDialog.setContentView(R.layout.custom_progressdialog);

        }

        @Override
		protected List<Competencia> doInBackground(String... params) {

        	if (cd.hayConexionAInternet()) {
        	
        		try {
        			LibretaClient client = getLibretaClient();
        			
        			if (client != null) {
						return client.Libreta_getDetalleByAlumno(mLogin, String.valueOf(SessionManager.perfilLogeado()), String.valueOf(mCGCodigo), String.valueOf(mBimestre));
        			} else
        				return null;
        			
        		} catch (Exception ex) {
        			return new ArrayList<Competencia>();
        		}
			
        	} else
        		return null;
			
		}

        @Override
        protected void onPostExecute(List<Competencia> comps) {
			
			progressDialog.dismiss();
			
			if (comps == null) {
				switchFragment(new NetworkLostFragment());
				return;
			}
			
			CompetenciaArrayAdapter adapter = new CompetenciaArrayAdapter(getActividad().getApplicationContext(), R.layout.competencias_list, comps, mNomBim);
			ListView lv = (ListView) getActividad().findViewById(R.id.lv_competencias);
			lv.setAdapter(adapter);
			
		}
        
    }
    
    private LibretaClient getLibretaClient() {
        
        String requestURI = SianetApplication.getRequestURI(getActividad());
		if (requestURI != null) {
	        if (client == null || !requestURI.equals(lastRequestURI)) {
	            BasicHttpParams params = new BasicHttpParams();
	            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
	            HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
	            HttpProtocolParams.setUseExpectContinue(params, false);
	            client = new LibretaHttpClient(getActividad());
	            lastRequestURI = requestURI;
	        }
	        return client;
		} else
			return null;
		
	}
    
    private void switchFragment(Fragment fragment) {
 		if (getActivity() == null)
 			return;
 		
 		if (getActivity() instanceof MainActivity) {
 			MainActivity ma = (MainActivity) getActivity();
 			ma.switchContent(fragment);
 		}
 	}
    
    private Activity getActividad(){
		return this.getActivity();
	}
    
}
